package org.abc.fund.controller.factorController;

import lombok.RequiredArgsConstructor;
import org.abc.fund.entity.factorEntity.FactorTree;
import org.abc.fund.entity.factorEntity.FactorTreeNode;
import org.abc.fund.service.factorService.FactorTreeService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
 * 因子树管理Controller
 */
@RestController
@RequestMapping("/factor-tree")
@CrossOrigin
@RequiredArgsConstructor
public class FactorTreeController {
    private final FactorTreeService factorTreeService;
    /**
     * 获取所有因子树（不分页）
     */
    @GetMapping
    public ResponseEntity<List<FactorTree>> getAllFactorTrees(
            @RequestParam(required = false) FactorTree.BusinessScenario businessScenario,
            @RequestParam(required = false) Boolean enabled) {
        return ResponseEntity.ok(factorTreeService.getAllFactorTrees(businessScenario, enabled));
    }
    /**
     * 创建因子树
     */
    @PostMapping
    public ResponseEntity<FactorTree> create(@RequestBody FactorTree factorTree) {
        return ResponseEntity.ok(factorTreeService.createFactorTree(factorTree));
    }
    /**
     * 更新因子树
     */
    @PutMapping("/{id}")
    public ResponseEntity<FactorTree> update(@PathVariable Long id, @RequestBody FactorTree factorTree) {
        return ResponseEntity.ok(factorTreeService.updateFactorTree(id, factorTree));
    }
    /**
     * 删除因子树
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        factorTreeService.deleteFactorTree(id);
        return ResponseEntity.ok().build();
    }
    /**
     * 根据ID查找因子树
     */
    @GetMapping("/{id}/id")
    public ResponseEntity<FactorTree> findById(@PathVariable Long id) {
        Optional<FactorTree> tree = factorTreeService.findById(id);
        return tree.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build());
    }
    /**
     * 根据业务场景查找因子树
     */
    @GetMapping("/scenario")
    public ResponseEntity<List<FactorTree>> getByBusinessScenario(
            @RequestParam FactorTree.BusinessScenario businessScenario) {
        return ResponseEntity.ok(
                factorTreeService.findByBusinessScenario(businessScenario)
        );
    }
    /**
     * 移动节点
     */
    @PatchMapping("/node/{nodeId}/move")
    public ResponseEntity<FactorTreeNode> moveNode(
            @PathVariable Long nodeId,
            @RequestParam(required = false) Long newParentId) {
        return ResponseEntity.ok(
                factorTreeService.moveNode(nodeId, newParentId)
        );
    }
    /**
     * 根据树名称模糊查找因子树
     */
    @GetMapping("/{name}/name")
    public ResponseEntity<List<FactorTree>>findByTreeNameContaining(@PathVariable String name) {
        List<FactorTree> trees = factorTreeService.findByTreeNameContaining(name);
        return trees.isEmpty()
                ? ResponseEntity.notFound().build()
                : ResponseEntity.ok(trees);
    }
    /**
     * 分页查询因子树
     */
    @GetMapping("/page")
    public ResponseEntity<Page<FactorTree>> page(
            @RequestParam(required = false) FactorTree.BusinessScenario businessScenario,
            @RequestParam(required = false) Boolean enabled,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        Pageable pageable = PageRequest.of(page, size);
        return ResponseEntity.ok(factorTreeService.findFactorTrees(businessScenario, enabled, pageable));
    }

    /**
     * 获取树结构
     */
    @GetMapping("/{treeId}/structure")
    public ResponseEntity<List<FactorTreeNode>> getTreeStructure(@PathVariable Long treeId) {
        return ResponseEntity.ok(factorTreeService.getTreeStructure(treeId));
    }

    /**
     * 创建树节点
     */
    @PostMapping("/node")
    public ResponseEntity<FactorTreeNode> createNode(@RequestBody FactorTreeNode node) {
        return ResponseEntity.ok(factorTreeService.createTreeNode(node));
    }

    /**
     * 更新树节点
     */
    @PutMapping("/node/{id}")
    public ResponseEntity<FactorTreeNode> updateNode(@PathVariable Long id, @RequestBody FactorTreeNode node) {
        return ResponseEntity.ok(factorTreeService.updateTreeNode(id, node));
    }

    /**
     * 删除树节点
     */
    @DeleteMapping("/node/{id}")
    public ResponseEntity<Void> deleteNode(@PathVariable Long id) {
        factorTreeService.deleteTreeNode(id);
        return ResponseEntity.ok().build();
    }

    /**
     * 获取根节点
     */
    @GetMapping("/{treeId}/rootNodes")
    public ResponseEntity<List<FactorTreeNode>> getRootNodes(@PathVariable Long treeId) {
        return ResponseEntity.ok(factorTreeService.getRootNodes(treeId));
    }

    /**
     * 获取子节点
     */
    @GetMapping("/node/{parentId}/children")
    public ResponseEntity<List<FactorTreeNode>> getChildNodes(@PathVariable Long parentId) {
        return ResponseEntity.ok(factorTreeService.getChildNodes(parentId));
    }
    /**
     * 检查树名称是否存在
     */
    @GetMapping("/exists")
    public ResponseEntity<Boolean> existsByTreeName(
            @RequestParam String treeName) {
        return ResponseEntity.ok(
                factorTreeService.existsByTreeName(treeName)
        );
    }
    /**
     * 获取节点深度
     */
    @GetMapping("/node/{nodeId}/depth")
    public ResponseEntity<Integer> getNodeDepth(@PathVariable Long nodeId) {
        return ResponseEntity.ok(
                factorTreeService.getNodeDepth(nodeId)
        );
    }
    /**
     * 搜索节点
     */
    @GetMapping("/{treeId}/node/search")
    public ResponseEntity<List<FactorTreeNode>> searchNodes(
            @PathVariable Long treeId,
            @RequestParam String keyword) {
        return ResponseEntity.ok(
                factorTreeService.searchNodes(treeId, keyword)
        );
    }
    /**
     * 复制节点
     */
    @PostMapping("/node/{nodeId}/copy")
    public ResponseEntity<FactorTreeNode> copyNode(
            @PathVariable Long nodeId,
            @RequestParam(required = false) Long targetParentId) {
        return ResponseEntity.ok(
                factorTreeService.copyNode(nodeId, targetParentId)
        );
    }
    /**
     * 批量更新节点
     */
    @PutMapping("/node/batch")
    public ResponseEntity<Void> batchUpdateNodes(
            @RequestBody Map<String, Object> request) {
        List<Long> nodeIds = (List<Long>) request.get("nodeIds");
        Map<String, Object> updates = (Map<String, Object>) request.get("updates");
        factorTreeService.batchUpdateNodes(nodeIds, updates);
        return ResponseEntity.ok().build();
    }
    /**
     * 获取节点子树
     */
    @GetMapping("/node/{nodeId}/subtree")
    public ResponseEntity<List<FactorTreeNode>> getSubtree(
            @PathVariable Long nodeId) {
        return ResponseEntity.ok(
                factorTreeService.getSubtree(nodeId)
        );
    }

}